class JobController < ApplicationController

  # Everything protected is only available to logged in users
  before_filter :protect
  before_filter :protect_for_otw, :only => [ :new, :create, :edit, :update ]
  before_filter :protect_for_volcom, :only => [ :list ]
  
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @display_data = Job.display_list(params[:page])
  end

  def show
    @job = Job.find(params[:id])
  end

  def new
    @job = Job.new
  end

  def create
    @job = Job.new(params[:job])
    if (get_user.is_otw || get_user.is_volcom) && @job.save && update_skills(@job)
      flash[:notice] = 'Job was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @job = Job.find(params[:id])
  end

  def update
    @job = Job.find(params[:id])
    if @job && (get_user.is_otw || get_user.is_volcom)
      if @job.update_attributes(params[:job]) && update_skills(@job)
        flash[:notice] = 'Job was successfully updated.'
        redirect_to :action => 'show', :id => @job
      else
        render :action => 'edit'
      end
    end
  end

  def destroy
    @job = Job.find(params[:id])
    if @job && (get_user.is_otw || get_user.is_volcom)
      @job.destroy
      redirect_to :action => 'list'
    else
      flash[:error] = 'You may not delete jobs.'
    end
  end

  # search for jobs with matching characteristics
  def job_search
    match_any = (params[:match_type] && params[:match_type] == "any")

    # full-text query matching
    query_hits = find_queried(params[:query], Job, :match_any => match_any)
    
    # skill matching
    @skills_to_match = Skill.find_all_skills.select {|skill| skill_checked?(skill)}
    skill_hits = find_skilled(@skills_to_match, Job, :match_any => match_any)
    
    # return only jobs which fit all criteria
    data = find_union(:query => params[:query], :query_hits => query_hits,
                      :skills => @skills_to_match, :skill_hits => skill_hits,
                      :match_any => match_any)

    if data.nil?
      data = Job.display_list(params)
    end
           
    unless params[:inactive]
      data = data & Job.find_all_by_is_open(true)
    end

    @display_data = data
    STDERR.puts "got here with data " + data.map {|job| job.title}.join(', ') + " jobs"
  end



  protected

    def update_skills(job)
      @skills = Skill.find_all_skills
      @skills.each do |skill|
        if params["skill_#{skill.id}"] && !job.has_skill(skill.id)
          job.add_skill(skill.id)
        elsif !params["skill_#{skill.id}"] && job.has_skill(skill.id)
          job.remove_skill(skill.id)
        end
      end
    end


end
